<template>
    <div class="box">
        <el-card>
            <template #header>
                <h3>基本信息</h3>
            </template>
            <!-- 个人信息编辑态 -->
            <el-form v-if="show === 'edit'" :model="user" label-width="120px" :rules="rules" ref="userInfoForm">
                <!-- 上传头像 -->
                <el-form-item label="头像" prop="avatar">
                    <el-upload class="avatar-uploader" action="http://127.0.0.1:8082/upload" :show-file-list="false"
                        :on-success="handleAvatarSuccess">
                        <el-avatar v-if="user.user_img" shape="circle" :size="150" :fit="'cover'"
                            :src="user.user_img" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="user.name"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="user.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="user.phone"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="update">保存</el-button>
                </el-form-item>
            </el-form>

            <!-- 个人信息浏览态 -->
            <el-form v-if="show === 'browse'" :model="user" label-width="120px" :rules="rules" ref="userInfoForm">
                <!-- 上传头像 -->
                <el-form-item label="头像" prop="avatar">
                    <el-avatar v-if="user.user_img" shape="circle" :size="150" :fit="'cover'" :src="user.user_img" />
                    <el-icon v-else src="src\assets\imgs\默认头像.png"></el-icon>
                </el-form-item>
                <el-form-item label="姓名" prop="">
                    <p v-text="user.name"></p>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <p v-text="user.email"></p>
                </el-form-item>
                <el-form-item label="手机号" prop="">
                    <p v-text="user.phone"></p>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="show = 'edit'">修改</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import { ref } from 'vue'
import { residentInfoUpdateAPI } from '@/api/resident';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import { adminUpdateAPI } from '@/api/user';
export default {
    data() {
        return {
            show: 'browse',
            size: ref < 'default' | 'large' | 'small' > ('default'),
            user: JSON.parse(sessionStorage.getItem('user')),
            rules: {
                name: { required: true, message: '姓名不能为空', trigger: 'blur' },
                email: [
                    { required: false, trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const emailRegex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                            if (value !== '') {
                                if (emailRegex.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error('请输入有效的邮箱地址'));
                                }
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                phone: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const phoneRegex = /^[0-9]{11}$/;
                            if (value !== '') {
                                if (phoneRegex.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error('请输入有效的手机号'));
                                }
                            }
                        },
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    methods: {
        update() {
            this.$refs.userInfoForm.validate((val) => {
                if (val) {
                    adminUpdateAPI(this.user).then((resp) => {
                        if (resp.data.code == 2000) {
                            // 记录原头像
                            let oldAvatar = JSON.parse(sessionStorage.getItem('user')).user_img;
                            // 更新session
                            sessionStorage.setItem('user', JSON.stringify(resp.data.data));
                            sessionStorage.setItem('message', resp.data.message);
                            if (oldAvatar != this.user.user_img) {
                                // 刷新页面
                                location.reload();
                            }
                            ElMessage.success(resp.data.message);
                            this.show = 'browse';
                            // this.loadAdminInfoList();
                        } else {
                            ElMessage.error(resp.data.message);
                        }
                    })
                }
            })
        },
        // 图片上传成功之后回调函数
        handleAvatarSuccess(response) {
            this.user.user_img = response;
        },
    },
    computed: {
        age() {
            if (this.user.birthdate == null) {
                return '选择出生日期计算年龄';
            }
            let birthDate = new Date(this.user.birthdate);
            let currentDate = new Date();
            let age = currentDate.getFullYear() - birthDate.getFullYear();
            let monthDifference = currentDate.getMonth() - birthDate.getMonth();
            if (monthDifference < 0 || (monthDifference === 0 && currentDate.getDate() < birthDate.getDate())) {
                age--;
            }
            this.user.age = age;
            if (age < 0 || age > 120) {
                return '出生日期不合理';
            }
            return age;
        },
    },
    mounted() {
        // 页面加载时检查并显示消息
        const message = sessionStorage.getItem('message');
        if (message) {
            ElMessage.success(message);
            // 清除消息
            sessionStorage.removeItem('message');
        }
    },
}
</script>

<style scoped>
.box {
    width: 100%;
    height: 100%;
}

.el-card {
    width: 600px;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>